# -*- coding: utf-8 -*-

__author__ = 'ggcall'

import re
import os
import requests
import json
import base64
import subprocess
from npedi import app, request_wants_json, sa, BASE_PATH, query_db
from models import CusMov, Auth
from flask import request, render_template, jsonify, redirect, url_for, Response, send_file
from datetime import datetime


def sarow2dict(rows):
    if type(rows) == tuple or type(rows) == list:
        l = []
        for row in rows:

            d = {}
            for column in row.__table__.columns:
                d[column.name] = getattr(row, column.name)

            l.append(d)

        return l
    else:
        return rows


def todict(items, usenone=True, delkey=None):
    # items:  是把request.form获得的ImmutableMultiDict对象用iteritems取得
    # usenone:是否把空值('')转换为None返回,默认转换为None
    # delkey: 是否删除指定的key,比如多余获取的input值,传入值可以是tuple或list,默认不删除
    d = {}
    for k, v in items:
        if v:
            d[k] = v
        elif usenone:
            d[k] = None
    if delkey:
        if type(delkey) == tuple or type(delkey) == list:
            for key in delkey:
                d.pop(key, None)
        else:
            d.pop(delkey, None)
    return d


def cleanhtml(html):
    pattern = '\s+|(&nbsp;)+'
    # pattern='\s+'
    html = re.sub(pattern, ' ', html)
    # 去掉html标记间的空格
    # pattern='> <'
    # html=re.sub(pattern,'><',html)
    return html.replace('> <', '><')


def cleanrow(row):
    for k in row.keys():
        if row[k] == '':
            row[k] = None
    return row


def response(res, callback=None):
    if callback:
        return Response(callback + "(" + json.dumps(res) + ")", mimetype='application/javascript')
    else:
        return jsonify(res)


@app.route('/')
def index():
    return jsonify(result=True)


@app.route('/auth_npedi', methods=['GET', 'POST'])
def auth_npedi():
    action = request.values.get('action', None)
    site = request.values.get('site', None)
    callback = request.values.get('callback', None)
    if request.method == "POST":
        cookie = request.form.get('cookie', None)
        print action, cookie, site
        if action == 'remote' and request_wants_json():
            auth = Auth.query.filter_by(site=site).first()

            print auth.cookie
            auth.cookie = cookie
            auth.refresh = datetime.strftime(
                datetime.now(), '%Y-%m-%d %H:%M:%S')
            print auth.cookie
            sa.session.commit()
            return jsonify(result=True)
    if request.method == 'GET':
        # if action == 'remote':
        if action == 'remote' and request_wants_json():
            auth = Auth.query.filter_by(site=site).first()
            res = dict(result=True, cookie=auth.cookie, refresh=auth.refresh)
            # response(res, callback)
            return Response(callback + "(" + json.dumps(res) + ")",
                            mimetype='application/javascript') if callback else jsonify(res)


@app.route('/pic2code', methods=['POST'])
def pic2code():
    pic_b64 = request.values.get('pic_b64', None)
    callback = request.values.get('callback', None)

    print pic_b64

    def randcode(pic):
        tesseract_cmd = os.path.join(BASE_PATH, 'tesseract.exe')
        source = os.path.join(BASE_PATH, 'code.jpg')
        dest = os.path.join(BASE_PATH, 'code')
        with open(source, 'wb') as f1:
            f1.write(base64.b64decode(pic))
        subprocess.call('%s %s %s digits' %
                        (tesseract_cmd, source, dest), stderr=subprocess.PIPE)
        # proc = subprocess.call('tesseract.exe code.jpg code digits', stderr=subprocess.PIPE)
        with open(dest + '.txt') as f2:
            t = f2.read()
        print 'txt:', t
        t = re.findall('\d', t.strip())
        if len(t) == 4:
            return ''.join(t)

    code = randcode(pic_b64)
    if code:
        res = dict(result=True, code=code)
    else:
        res = dict(result=False)
    print res
    return Response(callback + "(" + json.dumps(res) + ")", mimetype='application/javascript') if callback else jsonify(
        res)


@app.route('/query_npedi', methods=['GET'])
def query_npedi():
    callback = request.values.get('callback', None)
    # action=request.values.get('action',None)
    query_id = request.values.get('query_id', None)
    ctn_no = request.values.get('ctn_no', None)
    cookie = Auth.query.filter_by(site='npedi').first()
    print cookie
    # if action=='remote' and request_wants_json():
    with open(os.path.join(BASE_PATH, 'config.json')) as f:
        c = f.read()
    j = json.loads(c)
    p = j['app']['app%s' % query_id]
    rs = []
    try:
        url = 'http://www.npedi.com/edi/%s' % p['query_app']
        params = {p['query_param']: ctn_no}
        pattern = p['query_pattern']
        if p['query_ext_params']:
            ext_params = p['query_ext_params']
            for x in ext_params:
                params[x['key']] = x['val']
        cookies = dict(JSESSIONID=cookie.cookie)
        print url, params, cookies
        t = requests.get(url, params=params, cookies=cookies).text
        print pattern
        trs = re.findall(pattern, cleanhtml(t))
        print len(trs), trs
        for i in range(len(trs) / p['col_count']):
            r = []
            for idx, val in enumerate(trs[i * p['col_count']:(i + 1) * p['col_count']]):
                v = re.sub('<.+?>', '', val).strip()
                print v
                r.append(v)
            rs.append(r)
    except Exception, e:
        print e
    res = dict(id=p['query_id'], col=p['col_count'], name=p['query_name'], result=rs)
    return Response(callback + "(" + json.dumps(res) + ")", mimetype='application/javascript') if callback else jsonify(
        res)


@app.route('/query_nbedi', methods=['GET'])
def query_nbedi():
    callback = request.values.get('callback', None)
    s_type = request.values.get('s_type', None)
    s_text = request.values.get('s_text', '')
    query_id = request.values.get('query_id', None)
    rs = []
    if query_id == '1' and s_type == 'bill_no':
        t = requests.post('http://www.nbedi.com/h2000eport_ic/pre_bgd/entry_main/ExPreSearch.asp', data={
            'bill_no': s_text, 'traf_name': '', 'voyage_no': ''}, headers={
            'Referer': 'http://www.nbedi.com/h2000eport_ic/pre_bgd/entry_main/ExPreSearch.asp'}).text
        trs = re.findall('<div align="center">.*?</div>', t)
        col_count = 8
        for i in range(len(trs) / col_count):
            r = []
            for idx, val in enumerate(trs[i * col_count:(i + 1) * col_count]):
                r.append(
                    re.sub('<.+?>', '', val).strip().encode('raw_unicode_escape').decode('gbk'))
            rs.append(r)
    elif query_id == '2':
        def get_report(ctnno='', billno=''):
            req_url = u'http://61.175.135.173/MsFlat/ArrivalReportNew.aspx?__VIEWSTATE=e0c0uPrgm8N8wNqSew9WJqhoVwbamZKl0OKzdQ6YiP62mzmt/TWR/liZHpLWTMz1MG04CQQjdPXwm1L8iYEbcqUai5UgD17Iuppthzf99klzQ8pyzdBlgjfCvHVjsImZgXjc3SLfogHWsItLxLZ4NpYInRPDFKcaXsCAEQ==&__VIEWSTATEENCRYPTED=&__EVENTVALIDATION=YH/PNp6wLPyLntadgs1cAgkeAT2oBDNcaamtBY0aDyGxyg4uzKtHPRTbZvziMEXQtUUph6u9xYAcS00hCGxXuCTaQKfK3Mjo5BivX8iN0RFOZBZTQWj0vi3xGP2QVoe8ilCVYA==&txt_ContainerNO=%s&txt_ShipName=&txt_VoyageNo=&txt_StartDate=&txt_EndDate=&btn_Search=开始查询&Pager1_input=1&txt_BillNO=%s' % (
                ctnno, billno)
            print req_url
            html = requests.get(req_url).text
            # print res
            try:
                table = re.findall(
                    '<table[^>]*id=\"GridView1\"[^>]*>.+?</table>', html, re.S)[0]
                table = cleanhtml(table)
                # print table
                trs = re.findall('<tr><t[h|d].+?</t[h|d]></tr>', table)
                print len(trs)
                print trs
                for tr in trs:
                    tds = re.findall('<t[h|d].*?>(.+?)</t[h|d]>', tr, re.S)
                    # print tds
                    tds[10] = re.sub('<.*?>', '', tds[10])
                    print tds

                    rs.append(tds)
            except:
                pass
            print rs
            return rs

        bill_no = ''
        ctn_no = ''
        if s_type == 'bill_no':
            bill_no = s_text
        if s_type == 'ctn_no':
            ctn_no = s_text
        rs = get_report(ctn_no, bill_no)
    res = dict(id=query_id, result=rs)
    return Response(callback + "(" + json.dumps(res) + ")", mimetype='application/javascript') if callback else jsonify(
        res)


@app.route('/get_voyageinfo')
def get_voyageinfo():
    callback = request.values.get('callback', None)
    res = dict(result=query_db('select xh,tkmt,ywcm,zwcm,mthc,hx,undm,jxkssj,jxjzsj,jdsj from voyageinfo'))
    return Response(callback + "(" + json.dumps(res) + ")", mimetype='application/javascript') if callback else jsonify(
        res)


@app.route('/checkbox', methods=['GET', 'POST'])
def checkbox():
    callback = request.values.get('callback', None)
    if request.method == 'GET':
        boxno = request.args.get('boxno', None)
        vessel = request.args.get('vessel', None)
        voyage = request.args.get('voyage', None)
        instructtime = request.args.get('instructtime', None)
        # sql="select * from cusmov where boxno='%s' and vessel='%s' and voyage='%s' and instructtime>='%s'"%(box['box'],box['cd_voyage'].split('/')[0],box['cd_voyage'].split('/')[1],box['cd_date'])
        boxs = CusMov.query.filter_by(boxno=boxno).filter_by(vessel=vessel).filter_by(voyage=voyage).filter(
            CusMov.instructtime >= instructtime).all()
        res = dict(result=True if boxs else False)
        return Response(callback + "(" + json.dumps(res) + ")",
                        mimetype='application/javascript') if callback else jsonify(res)
    if request.method == 'POST':
        box_id = json.loads(request.form.get('box_id'))
        box = json.loads(request.form.get('box'))
        cd_date = json.loads(request.form.get('cd_date'))
        cd_voyage = json.loads(request.form.get('cd_voyage'))
        result = []
        for i in xrange(len(box_id)):
            vessel, voyage = cd_voyage[i].split('/')
            boxs = CusMov.query.filter_by(boxno=box[i]).filter_by(vessel=vessel).filter_by(voyage=voyage).filter(
                CusMov.instructtime >= cd_date[i]).all()
            if boxs:
                result.append(box_id[i])
                print box[i], True
        res = dict(result=result)
        return Response(callback + "(" + json.dumps(res) + ")",
                        mimetype='application/javascript') if callback else jsonify(res)
